My Learning Channel

try-except语句

2022-09-18

try-except语句

介绍

try-except : 处理异常

1
2
3
4
5
6
try:
# 执行要尝试 (try) 的代码
except
# 执行应对异常发生时的代码

#Python 从 try 子句开始执行,若一切正常,则跳过 except 子句;若发生异常,则跳出 try 子句,执行 except 子句。

1. try-except捕获异常:

1
2
3
4
5
6
try:
file = open('test.py') # 不存在的文件
print('Everything went well!') # 打印顺利运行提示信息
except:
print('Something went wrong!') # 处理异常方式:打印错误提示信息

Something went wrong!

2. try-except 捕获具体异常:

1
2
3
4
5
try:
file = open('test.py') # 不存在的文件
print('Everything went well!') # 打印顺利运行提示信息
except Exception as e: #把Exception 错误保存在变量e中
print('Something went wrong!',e) # 处理异常方式:打印错误提示信息
Something went wrong! [Errno 2] No such file or directory: 'test.py'

3. try-except 对异常进行分别处理:

1
2
3
4
5
6
7
try:
file = open('test.py')
print('Everything goes well!')
except FileExistsError as e: # 捕获特定类型异常
print('There is a FileExistsError!',e)
except FileNotFoundError as e: # 捕获特定类型异常
print('There is a FileNotFoundError!',e)
There is a FileNotFoundError! [Errno 2] No such file or directory: 'test.py'

python常见的异常类型

1. NameError:尝试访问一个未申明的变量:

1
2
v

---------------------------------------------------------------------------

NameError                                 Traceback (most recent call last)

Input In [25], in <cell line: 1>()
----> 1 v


NameError: name 'v' is not defined

2. ZeroDivisionError:除数为0:

1
v = 1/0
---------------------------------------------------------------------------

ZeroDivisionError                         Traceback (most recent call last)

Input In [22], in <cell line: 1>()
----> 1 v = 1/0


ZeroDivisionError: division by zero

3. SyntaxError:语法错误:

1
int int
  Input In [23]
    int int
        ^
SyntaxError: invalid syntax

4. IndexError:索引超出范围:

1
2
List = [2]
List[3]
---------------------------------------------------------------------------

IndexError                                Traceback (most recent call last)

Input In [26], in <cell line: 2>()
      1 List = [2]
----> 2 List[3]


IndexError: list index out of range

5. KeyError:字典关键字不存在:

1
2
Dic = {'1':'yes', '2':'no'}
Dic['3']
---------------------------------------------------------------------------

KeyError                                  Traceback (most recent call last)

Input In [27], in <cell line: 2>()
      1 Dic = {'1':'yes', '2':'no'}
----> 2 Dic['3']


KeyError: '3'

6. IOError:输入输出错误:

1
f = open('abc')
---------------------------------------------------------------------------

FileNotFoundError                         Traceback (most recent call last)

Input In [28], in <cell line: 1>()
----> 1 f = open('abc')


FileNotFoundError: [Errno 2] No such file or directory: 'abc'

7. AttributeError:访问未知对象属性:

1
2
3
4
5
6
class Worker:
def Work():
print("I am working")

w = Worker()
w.a
---------------------------------------------------------------------------

AttributeError                            Traceback (most recent call last)

Input In [41], in <cell line: 6>()
      3     print("I am working")
      5 w = Worker()
----> 6 w.a


AttributeError: 'Worker' object has no attribute 'a'

8. ValueError:数值错误:

1
int('d')
---------------------------------------------------------------------------

ValueError                                Traceback (most recent call last)

Input In [42], in <cell line: 1>()
----> 1 int('d')


ValueError: invalid literal for int() with base 10: 'd'

9. TypeError:类型错误:

1
2
3
iStr = '22'
iVal = 22
obj = iStr + iVal
---------------------------------------------------------------------------

TypeError                                 Traceback (most recent call last)

Input In [43], in <cell line: 3>()
      1 iStr = '22'
      2 iVal = 22
----> 3 obj = iStr + iVal


TypeError: can only concatenate str (not "int") to str

10. AssertionError:断言错误:

1
assert 1 != 1
---------------------------------------------------------------------------

AssertionError                            Traceback (most recent call last)

Input In [44], in <cell line: 1>()
----> 1 assert 1 != 1


AssertionError: 

11. MemoryError:内存耗尽异常:

12. NotImplementedError:方法没实现引起的异常:

1
2
3
4
5
6
7
class Base(object):
def __init__(self):
pass

def action(self):
#抛出异常,说明该接口方法未实现
raise NotImplementedError

13. LookupError:键、值不存在引发的异常:

LookupError异常是IndexError、KeyError的基类, 如果你不确定数据类型是字典还是列表时,可以用LookupError捕获此异常

14. StandardError 标准异常:

除StopIteration, GeneratorExit, KeyboardInterrupt 和SystemExit外,其他异常都是StandarError的子类。

1

使用支付宝打赏
使用微信打赏

若你觉得我的文章对你有帮助,欢迎点击上方按钮对我打赏

扫描二维码,分享此文章